package com.mobipe.sutto.mina;

import java.nio.ByteBuffer;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.mobipe.sutto.core.AbstractServer;
import com.mobipe.sutto.core.InterfaceServerHandler;
import com.mobipe.sutto.core.ProtocolProcess;

/**
 * @author kohachiro
 *
 */
public class ServerHandler extends IoHandlerAdapter implements InterfaceServerHandler{

	public ServerHandler(){
		AbstractServer.callbackHandler=this;
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// LOGGER.info("CLOSED");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {

	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) {

	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) {
		session.close(true);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		ProtocolProcess.protocolHandler(((IoBuffer)message).buf(),session);
	}

	@Override
	public void sendResponse(ByteBuffer message, Object channel) throws Exception {
		((IoSession)channel).write(IoBuffer.wrap(message));
		
	}
	@Override
	public void sendResponseClose(ByteBuffer message, Object channel) throws Exception {
		((IoSession)channel).write(IoBuffer.wrap(message)).addListener(IoFutureListener.CLOSE);
	}
	@Override
	public int getId(Object channel) {
		return (int) ((IoSession)channel).getId();
	}	
}